const _function = require("../../utils/functionData.js")
Page({
  data: {
    videoPath: '',
    videoUrl: '',
    uploadProgress: 0,
    title: '',
    categories: ['高等数学', '大学英语', '计算机基础'],
    selectedCategory: '',
    learningGoal: '',
    deadline: '',
    duration: '',
    isFormValid: false,
    formData: {
      title: '',
      learningGoal: '',
    }
  },
  onShow() {
    if (this.getTabBar) {
      this.getTabBar().setData({
        selected: 3 // 根据当前页面设置选中状态
      });
    }
  },
  // 选择视频
  // chooseVideo() {
  //   let that = this
  //   wx.chooseMedia({
  //     type: 'video',
  //     success: res => {
  //       console.log(123);
  //       this.setData({ videoPath: res.tempFilePath })
  //       console.log('videoPath',this.data.videoPath);
  //       this.checkFormValid()
  //     }
  //   })
  // },
  chooseVideo: function () {
    var _this = this;

    wx.chooseMedia({
      count: 1,
      mediaType: ['image', 'video'],
      sourceType: ['album', 'camera'],
      maxDuration: 30,
      camera: 'back',
      success(res) {
        let videoSrc = res.tempFiles[0].tempFilePath
        // 上传视频
        wx.uploadFile({
          header: {
            'content-type': 'application/x-www-form-urlencoded; charset=UTF-8',
            'Authorization': getApp().globalData.token
          },
          filePath: videoSrc,
          name: 'file',
          url: wx.getStorageSync('img_url') + '/common/upload',
          success: (e) => {
            let data = JSON.parse(e.data)
            console.log('上传视频成功', data);
            if (data.code == 200) {
              _this.setData({
                videoPath: data.url,
                videoUrl: data.fileName,
                // isFormValid:true
              })
              _this.checkFormValid()
            } else {
              wx.showToast({
                title: '视频上传错误！',
                icon: 'none'
              })
            }
          },
          fail: (res) => { },
          complete: (res) => { },
        })

      }
    })
  },
  /**
   * 上传视频 目前后台限制最大100M, 以后如果视频太大可以选择视频的时候进行压缩
   */
  // uploadvideo: function () {
  //   let _this = this
  //   let videoSrc = _this.data.videoSrc;

  //   if (!videoSrc) {
  //     wx.showToast({
  //       title: '请上传承诺视频',
  //       icon: 'none'
  //     })
  //   } else {
  //     let datas = {
  //       id: _this.data.id,
  //       acceptanceVideo: videoSrc
  //     }
  //     _function.postOnlineCommitment(datas, _this.postOnlineCommitmentBack, _this)
  //   }
  // },
  // 检查表单有效性
  checkFormValid() {
    const valid = this.data.videoPath &&
      this.data.title &&
      this.data.learningGoal
    this.setData({ isFormValid: valid })
  },
  // 获取视频时长
  getLength(e) {
    e.detail.duration = parseInt(e.detail.duration)
    //处理时间格式并存放到data中
    this.setData({
      duration: parseInt(e.detail.duration / 60) + ":" + e.detail.duration % 60
    })
    console.log('duration', this.data.duration);
  },
  // 监听输入框变化
  // onFieldChange(e) {
  //   const field = e.currentTarget.dataset.field; // 获取字段名
  //   const value = e.detail; // 获取输入值
  //   this.setData({
  //     [`formData.${field}`]: value // 更新 data
  //   });
  //   // console.log('改变',value,field,this.data.formData);
  // },
  onFieldChange(e) {
    const field = e.currentTarget.dataset.field;  // 获取字段名
    const value = e.detail.value;  // 获取输入值
    this.setData({ 
      [`formData.${field}`]: value // 更新 data
    });
    console.log(' 改变', value, field, this.data.formData); 
  },
  // 提交表单
  submitForm() {
    if (!this.data.formData.title||!this.data.formData.learningGoal || !this.data.videoUrl ) return

    // name 视频名称
    // introduce 学习目标
    // isPublish 是否发布（‘Y’, 'N'） 默认是
    // duration 时长
    // url 
    // uploadId 上传人ID
    const params = {
      name: this.data.formData.title,
      introduce: this.data.formData.learningGoal,
      url: this.data.videoUrl,
      // isPublish: 'Y',
      duration: this.data.duration,
      uploadId: getApp().globalData.userInfo.userId
    }
    console.log('params', params);
    _function.putAddVideo(params, this.putAddVideoBack, this)
    // console.log('提交的学习计划：', formData);
  },

  putAddVideoBack(res) {
    let dataAll = res.data
    if (dataAll.code == 200) {
      this.setData({
        formData:{},
        videoPath: '',
        videoUrl: '',
        duration: ''
      })
      wx.showToast({
        title: dataAll.msg,
        icon: 'none',
        duration: 1500,
        mask: true,
        success: () => {
        }
      });
    }
  },
})